package krow.dev.addetector.view;

import krow.dev.addetector.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircularImageView extends ImageView {
	
	private Paint mPaint;
	
	public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initialize(context);
	}

	public CircularImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initialize(context);
	}

	public CircularImageView(Context context) {
		super(context);
		initialize(context);
	}
	
	private void initialize(Context context){
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setColor(getResources().getColor(R.color.teal));
	}
	
	private void setCircularDrawable(Bitmap bitmap){
		
		CircularDrawable circleDrawable = new CircularDrawable(bitmap);
		setImageDrawable(circleDrawable);
	}
	
	@Override
	public void setImageBitmap(Bitmap bitmap) {
		setCircularDrawable(bitmap);
	}

	@Override
	public void setImageResource(int resId) {
		super.setImageResource(resId);
		
		Bitmap bitmap = null;
		Drawable drawable = getDrawable();
		if (drawable instanceof BitmapDrawable) {
			bitmap = ((BitmapDrawable) drawable).getBitmap();
		} else {
			return ;
		}
		setCircularDrawable(bitmap);
	}
	
	@Override
	public void setImageDrawable(Drawable drawable) {
		super.setImageDrawable(drawable);

		Bitmap bitmap = null;
		if (drawable instanceof BitmapDrawable) {
			bitmap = ((BitmapDrawable) drawable).getBitmap();
		} else {
			return ;
		}
		setCircularDrawable(bitmap);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		drawBackground(canvas);
		if(getDrawable() instanceof CircularDrawable){
			super.onDraw(canvas);
		}
	}
	
	private void drawBackground(Canvas canvas){
		int width = getMeasuredWidth() / 2;
		int height = getMeasuredHeight() / 2;
		
		canvas.drawCircle(
				width,
				height,
				Math.min(width, height),
				mPaint);
	}
}
